package com.youxin.busfoundation.common.es;

import com.youxin.busfoundation.bean.ent.RequestCompanyInfoBean;
import com.youxin.busfoundation.common.GlobalConfig;
import com.youxin.busfoundation.common.es.bean.CompanyBaseBean;
import com.youxin.busfoundation.config.EsConfig;
import com.youxin.foundation.lang.BaseException;
import com.youxin.foundation.utils.JsonUtils;
import com.youxin.foundation.utils.StringUtils;
import com.youxin.foundation.utils.collections.CollectionsUtils;

import org.apache.lucene.queryparser.classic.QueryParser;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @desc 搜索-企业详情相关
 * @author Kris.wang
 * @date 2017-12-05
 */
public class SearchCompanyInfo extends BaseSearch{

    /**
     * @desc 搜索企业信息
     * @param requestBean
     * @param include
     * @return
     * @throws Exception
     */
    public CompanyBaseBean queryCompanyInfo(RequestCompanyInfoBean requestBean, String[] include) throws Exception {
        try {
            // 构建ES客户端
            Client client=EsClient.instance().getClient();
            // 设置ES搜索索引
            SearchRequestBuilder builder = client.prepareSearch(EsConfig.getConfig().getCompanyname());
            // 设置ES搜索类型
            builder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setExplain(true);
            // 查询构造器
            builder.setQuery(
                    QueryBuilders.termQuery("uid", requestBean.getUid())
            );
            // 设置查询字段
            if (include.length > 0) {
                builder.setFetchSource(include,null);
            }
            // 执行查询
            SearchResponse response = builder.execute().actionGet(GlobalConfig.ES_SEARCH_TIMEOUT);

            // 查询结果为1条记录
            SearchHits hits = response.getHits();
            if (hits.getTotalHits() > 0) {
            	Map<String, Object> sourceMaps = hits.getAt(0).getSource();
            	String sourceString=JsonUtils.objectToFasterxmlJsonString(sourceMaps);
            	CompanyBaseBean  companyBaseBean = JsonUtils.stringToFasterxmlObject(sourceString, CompanyBaseBean.class);
                if (companyBaseBean == null) {
                	//logger.error("queryCompanyInfo:error:"+StringUtils.isNullSetEmpty(sourceString));
                    throw new BaseException("queryCompanyInfo:error数据转换错误"+StringUtils.isNullSetEmpty(sourceString));
                }else{
                	//logger.error("queryCompanyInfo:"+StringUtils.isNullSetEmpty(sourceString));
                }
                return companyBaseBean;
            }
            throw new BaseException("企业标识没有匹配到数据!");
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * @desc 公司uid搜索公司信息一次查询
     * @description
     * @param uids
     * @return
     * @throws Exception
     */
    public List<CompanyBaseBean> queryCompanyInfos(List<String> uids) throws Exception {
        try {
            Client client = EsClient.instance().getClient();
            SearchRequestBuilder srb = client.prepareSearch(EsConfig.getConfig().getCompanyname());
            srb.setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setFrom(0).setSize(1000).setExplain(true);
            String[] terms = uids.toArray(new String[] {});
            srb.setQuery(QueryBuilders.termsQuery("uid", terms));
            String[] include = {"full_name","uid","logo_url"};
            srb.setFetchSource(include,null);
            SearchResponse response = srb.execute().actionGet(GlobalConfig.ES_SEARCH_TIMEOUT);
            SearchHits hits = response.getHits();
            List<CompanyBaseBean> list = new ArrayList<>(20);
            for (SearchHit item : hits) {
                String sourceString = item.getSourceAsString();
                CompanyBaseBean bean = JsonUtils.stringToFasterxmlObject(sourceString, CompanyBaseBean.class);
                if (bean == null) {
                    throw new BaseException("数据转换错误");
                }
                list.add(bean);
            }
            return list;
        } catch (Exception e) {
            throw e;
        } finally {
        }
    }
}
